package util;


import java.util.ArrayList;

import model.Input;
import model.SimpleSequence;
import optimizers.commons.GAConstants;

import optimizers.ganeat.*;
import optimizers.ganeat.amplify.ConstantsAmply;

import org.apache.commons.math3.ode.sampling.StepHandler;
import org.apache.commons.math3.ode.sampling.StepInterpolator;

public class MyStepHandlerAmplify extends MyStepHandler {

	protected int Jcount = ConstantsAmply.pulseDuration+1;
	protected int lastPulse = -1;
	public ArrayList<Integer> spikes = new ArrayList<Integer>();
	public Input[] inputs; // the integer is the index in the y state array


	
	
	public MyStepHandlerAmplify(int sizeSimpleSeq, MyEventHandler myEventHandler){
		super(sizeSimpleSeq,myEventHandler);
	}

	@Override
	public void handleStep(StepInterpolator step, boolean isLastStep) {
		StepInterpolator localCopy = step.copy();
		if(step.getCurrentTime()>=time+1 && time<model.Constants.numberOfPoints-1){
			time++;
			localCopy.setInterpolatedTime(time);
			double[] y0 = localCopy.getInterpolatedState();
			int offset = 0;
			int dim = Math.min(sizeSimpleSeq,y0.length);
			int sizeIndiv = y0.length/this.repetitions;
			for(int repet=0; repet<this.repetitions; repet++){
				for(int i=0;i<dim;i++){
					this.timeSerie[i+offset][time]=y0[i+repet*sizeIndiv];
				}
				offset += dim;
			}
			
			if(myEventHandler.inputs[0].timeStep != lastPulse){
				lastPulse = myEventHandler.inputs[0].timeStep;
				spikes.add(lastPulse);
				Jcount = 0; 
			}
			
			//Judge square handeling
			if(Jcount >= ConstantsAmply.pulseDuration){
				//((SimpleSequence)inputs[0].seq).protectedSequence = false;
			}
			Jcount++;
			
		}
		
		
		
		
		

	}

	@Override
	public void init(double t0, double[] y0, double t) {
		// Be careful that this is only valid if the init is done for time t=0
		this.timeSerie = new double[this.repetitions*Math.min(sizeSimpleSeq,y0.length)][(this.simple?model.Constants.maxTimeSimple:model.Constants.numberOfPoints)];
		//System.out.println(Math.min(sizeSimpleSeq,y0.length));
		
		int offset = 0;
		int dim = Math.min(sizeSimpleSeq,y0.length);
		int sizeIndiv = y0.length/this.repetitions;
		for(int repet=0; repet<this.repetitions; repet++){
			for(int i=0;i<dim;i++){
				this.timeSerie[i+offset][0]=y0[i+repet*sizeIndiv];
			}
			offset += dim;
		}
	}

}
